var express = require("express");
var createError = require("http-errors");

const md5 = require("md5");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var expressJWT = require("express-jwt"); // 验证码客户端的token
var session = require("express-session"); // 验证码客户端的token
const {
  ForbiddenError,
  ServiceError,
  UnknownError,
} = require("./utils/errors");
// 默认读取项目根目录下.env
require("dotenv").config();
var app = express();
app.use(
  session({
    secret: process.env.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
  })
);

require("express-async-errors");
// 引入数据库
require("./dao/db");
var captchaRouter = require("./routes/captcha");
var adminRouter = require("./routes/admin");
var bannerRouter = require("./routes/banner");
var uploadRouter = require("./routes/upload");
var blogTypeRouter = require("./routes/blogType");
var blogRouter = require("./routes/blog");
var usersRouter = require("./routes/users");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
// 配置token接口
app.use(
  expressJWT
    .expressjwt({
      secret: md5(process.env.JWT_SECRET),
      algorithms: ["HS256"], //新版本expressJWT必须要求指定算法
    })
    .unless({
      // 哪些路由不需要验证
      path: [
        { url: "/admin/login", methods: ["POST"] },
        { url: "/res/captcha", methods: ["GET"] },
        { url: "/banner", methods: ["GET"] },
      ],
    })
);

// 使用路由中间件
// app.use("/", indexRouter);
app.use("/admin", adminRouter);
app.use("/res/captcha", captchaRouter);
app.use("/banner", bannerRouter);
app.use("/upload", uploadRouter);
app.use("/blogType", blogTypeRouter);
app.use("/blog", blogRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get("env") === "development" ? err : {};
  console.log("err.name===>", err.name);
  console.log("err.message===>", err.message);
  if (err.name === "UnauthorizedError") {
    let er = new ForbiddenError("未登录,或者登录已过期").toResponseJSON();
    res.send(er);
  } else if (err instanceof ServiceError) {
    res.send(err.toResponseJSON());
  } else {
    res.send(new UnknownError().toResponseJSON());
  }
});

module.exports = app;
